package com.xulu.romance.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xulu.romance.pojo.Article;
import com.xulu.romance.pojo.Question;
import com.xulu.romance.service.ArticleService;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.utils.PageUtils;
import com.xulu.romance.utils.R;
import com.xulu.romance.vo.ArchiveArticleVo;
import com.xulu.romance.vo.ArchiveQuestionVo;
import com.xulu.romance.vo.ArticleVo;
import com.xulu.romance.vo.QuestionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @version 1.0
 * @Author xiaoxulu
 * @Date 2024/1/13 21:55
 */

@RestController
@CrossOrigin
@RequestMapping("/api/article")
@Api(tags = "文章")
@Slf4j
public class ArticelController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/findAll")
    @ApiOperation("查询所有")
    public R findAll(){
        List<Article> articleList = articleService.list();
        return R.ok().put("articleList",articleList);
    }

    @GetMapping("/findAll/{currentPage}/{size}")
    @ApiOperation("分页查询")
    public R findPage(@PathVariable Long currentPage, @PathVariable Long size, Article condition) {
        // 创建分页对象
        IPage<Article> page = new Page<>(currentPage, size);

        // 构建查询条件
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (condition != null) {
            // 如果条件不为空，添加相应的查询条件
            if (StringUtils.isNotBlank(condition.getArticleTitle())) {
                queryWrapper.like("article_title", condition.getArticleTitle());
            }
        }
        // 根据创建时间降序排序
        queryWrapper.orderByDesc("update_time");

        // 执行分页查询
        IPage<Article> articleIPage = articleService.page(page, queryWrapper);

        // 获取查询结果
        List<Article> articleList = articleIPage.getRecords();
        long total = articleIPage.getTotal();

        // 返回结果
        return Objects.requireNonNull(R.ok().put("articleList", articleList)).put("count",total);
    }



    @GetMapping("/list")
    @ApiOperation("多表查询文章详情")
    public R list(@RequestParam Map<String, Object> params){
        //1.查询数量
        Integer count = articleService.findArticleDetailCount();

        //3.获取分页参数
        int currentPage = Integer.parseInt(params.get("currentPage").toString());
        int size = Integer.parseInt(params.get("size").toString());
        //2.获取条件参数
        String key = params.get("key").toString().trim();
        //5.定义集合用于接受数据
        List<ArticleVo> articleVoList;
        //6.判断查询条件是为为空
        if (org.apache.commons.lang.StringUtils.isNotBlank(key)){
            articleVoList=articleService.findArticleDetailCondition((currentPage-1)*size,size,key);
        }else {
            articleVoList=articleService.findArticleDetail((currentPage-1)*size,size);
        }

        PageUtils page=new PageUtils(articleVoList,count,size,currentPage);

        return R.ok().put("page", page);
    }

    @GetMapping("/front/list")
    @ApiOperation("多表查询文章详情")
    public R frontList(@RequestParam Map<String, Object> params){
        //1.查询数量
        Integer count = articleService.findArticleDetailCount();

        //3.获取分页参数
        int currentPage = Integer.parseInt(params.get("currentPage").toString());
        int size = Integer.parseInt(params.get("size").toString());
        //2.获取条件参数
        String key = params.get("key").toString().trim();
        //5.定义集合用于接受数据
        List<ArticleVo> articleVoList;
        //6.判断查询条件是为为空
        if (org.apache.commons.lang.StringUtils.isNotBlank(key)){
            articleVoList=articleService.findArticleDetailCondition((currentPage-1)*size,size,key);
        }else {
            articleVoList=articleService.findArticleDetail((currentPage-1)*size,size);
        }

        PageUtils page=new PageUtils(articleVoList,count,size,currentPage);

        if (articleVoList.isEmpty()){
            return new R().put("code",Constant.FAILURE_CODE).put("msg",Constant.SEARCH_FAILURE);
        }

        return Objects.requireNonNull(R.ok().put("page", page)).put("code",Constant.SUCCESS_CODE);
    }



    @GetMapping("/findById/{id}")
    @ApiOperation("根据id查询")
    public R findById(@PathVariable Integer id){
        Article article = articleService.getById(id);
        return R.ok().put("article",article);
    }


    @GetMapping("/front/findArticleDetailById/{id}")
    @ApiOperation("根据id查询详情")
    public R findArticleDetailById(@PathVariable Integer id){
        ArticleVo articleVo = articleService.findArticleDetailById(id);
        return R.ok().put("articleVo",articleVo);
    }

    @PostMapping("/save")
    @ApiOperation("添加文章")
    public R save(@RequestBody   Article article){

        try {
            boolean save = articleService.save(article);
            if (!save){
                return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.SAVE_FAILURE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.SAVE_SUCCESS);
    }

    @PostMapping("/update")
    @ApiOperation("更新文章")
    public R update(@RequestBody Article article){
                       boolean save = articleService.updateById(article);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.UPDATE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.UPDATE_SUCCESS);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除文章")
    public R delete(@PathVariable Integer id){
        boolean save = articleService.removeById(id);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }


    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除文章")
    public R deleteBatch(@RequestBody List<Integer> ids){
        boolean save = articleService.removeBatchByIds(ids);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }

    @GetMapping("/export")
    @ApiOperation("导出文章")
    public void export(HttpServletResponse response) throws Exception {
        List<ArticleVo> list = articleService.findAll();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id","id");
        writer.addHeaderAlias("articleTitle","文章标题");
        writer.addHeaderAlias("articleContent","文章内容");
        writer.addHeaderAlias("articleHover","文章封面");
        writer.addHeaderAlias("articleType","文章类型");
        writer.addHeaderAlias("articleTag","文章标签");
        writer.addHeaderAlias("likeNumber","点赞数量");
        writer.addHeaderAlias("collectNumber","收藏数量");
        writer.addHeaderAlias("browerNumber","浏览数量");

        writer.setOnlyAlias(true);

        writer.write(list,true);

        // 设置response参数
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String name = URLEncoder.encode("文章", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    @ApiOperation("导入文章")
    public R importUser(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Article> articleList = reader.readAll(Article.class);
        boolean save = articleService.saveBatch(articleList);
        if (!save){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.IMPORT_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.IMPORT_SUCCESS);
    }

    @GetMapping("/getArticleCount")
    @ApiOperation("文章数量")
    public R getArticleCount(){
        long count = articleService.count();
        return new R().put("count",count);
    }


    @GetMapping("/front/findArticleByTag/{currentPage}/{size}/{tagId}")
    @ApiOperation("根据类型查询试题")
    public R findArticleByTag(@PathVariable Integer currentPage, @PathVariable Integer size,@PathVariable Integer tagId ){
        List<ArticleVo> articleVoList = articleService.findArticleByTag((currentPage-1)*size,size, tagId);
        if (articleVoList.isEmpty()){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("msg",Constant.SEARCH_FAILURE);
        }
        Integer count = articleService.findArticleByTagCount(tagId);
        return Objects.requireNonNull(Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("articleVoList", articleVoList)).put("count",count);

    }

    @GetMapping("/front/updateBrowseNumber/{id}")
    @ApiOperation("浏览数量+1")
    public R updateBrowseNumber(@PathVariable Integer id){
        Article article = articleService.getById(id);
        Integer browerNumber = article.getBrowerNumber();
        browerNumber++;
        article.setBrowerNumber(browerNumber);
        articleService.updateById(article);
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("msg",Constant.UPDATE_SUCCESS);

    }

    @GetMapping("/front/findArchiveArticleList/{currentPage}/{size}")
    @ApiOperation("查询归档")
    public R findArchiveArticleList(@PathVariable Integer currentPage, @PathVariable Integer size ){
        List<ArchiveArticleVo> archiveArticleList = articleService.findArchiveArticleList((currentPage - 1) * size, size);
        if (archiveArticleList.isEmpty()){
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("msg",Constant.SEARCH_FAILURE);
        }
        long count = articleService.count();
        return Objects.requireNonNull(Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("archiveArticleList", archiveArticleList)).put("count",count);

    }
}
